using Newtonsoft.Json;
using LiJ.Common.Core;
using LiJ.Http.Extention;
using LiJ.Http.Mos;
using LiJ.Framework.Official.Basic.Mos;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LiJ.Framework.Official.Basic
{
	/// <summary>
	///  素材管理接口
	/// </summary>
	public class WxOffMediaApi : WxOffBaseApi
	{
		/// <summary>
		///
		/// </summary>
		/// <param name="config">配置信息，如果这里不传，需要在程序入口静态 WxBaseApi.DefaultConfig 属性赋值</param>
		public WxOffMediaApi(AppConfig config = null)
			: base(config)
		{
		}

		/// <summary>
		/// 上传素材接口【临时素材】
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public async Task<WxMediaTempUploadResp> UploadTempMediaAsync(WxMediaTempUploadReq request)
		{
			LHttpRequest LHttpRequest = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/media/upload?type=" + request.type.ToString()
			};
			LHttpRequest.FileParameters.Add(new FileParameter("media", request.file_stream, request.file_name, request.content_type));
			return await base.RestCommonOffcialAsync<WxMediaTempUploadResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取素材【临时素材】 文件流
		/// </summary>
		/// <param name="mediaId"></param>
		/// <returns></returns>
		public async Task<WxFileResp> DownloadTempMediaAsync(string mediaId)
		{
			WxOffAccessTokenResp wxOffAccessTokenResp = await this.GetAccessTokenFromCacheAsync();
			if (!wxOffAccessTokenResp.IsSuccess())
			{
				return ((ResultMo)wxOffAccessTokenResp).ConvertToResult<WxFileResp>();
			}
			return await new LHttpRequest
			{
				HttpMothed = HttpMothed.Get,
				AddressUrl = "https://api.weixin.qq.com" + string.Format("/cgi-bin/media/get?access_token={0}&media_id={1}", wxOffAccessTokenResp.access_token, mediaId)
			}.RestCommon(WxOffBaseApi.DownLoadFileAsync, null, "default");
		}

		/// <summary>
		///  获取视频素材【临时素材】下载地址
		/// </summary>
		/// <param name="mediaId"></param>
		/// <returns></returns>
		public async Task<WxMediaTempVideoUrlResp> GetTempMediaVedioUrlAsync(string mediaId)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Get,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/media/get?media_id=" + mediaId
			};
			return await base.RestCommonOffcialAsync<WxMediaTempVideoUrlResp>(req, null);
		}

		/// <summary>
		/// 添加永久微信图文素材（文章组合）
		/// </summary>
		/// <param name="list"></param>
		/// <returns></returns>
		public async Task<WxMediaResp> AddArticleGroupAsync(IList<WxArticleInfo> list)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/add_news";
			LHttpRequest.CustomBody = JsonConvert.SerializeObject(new
			{
				articles = list
			});
			return await base.RestCommonOffcialAsync<WxMediaResp>(LHttpRequest, null);
		}

		/// <summary>
		///  上传图片并获取地址
		///      没有mediaId【图文】【微店】
		/// </summary>
		/// <param name="imgReq"></param>
		/// <returns></returns>
		public async Task<WxArticleUploadImgResp> UploadFreeImageAsync(WxFileReq imgReq)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/media/uploadimg";
			LHttpRequest.FileParameters.Add(new FileParameter("media", imgReq.file_stream, imgReq.file_name, imgReq.content_type));
			return await base.RestCommonOffcialAsync<WxArticleUploadImgResp>(LHttpRequest, null);
		}

		/// <summary>
		///   获取图文素材（文章组合）
		/// </summary>
		/// <param name="mediaId">素材</param>
		/// <returns></returns>
		public async Task<WxGetArticleGroupResp> GetArticleGroupAsync(string mediaId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/get_material";
			LHttpRequest.CustomBody = string.Format("{{\"media_id\":\"{0}\"}}", mediaId);
			return await base.RestCommonOffcialAsync<WxGetArticleGroupResp>(LHttpRequest, null);
		}

		/// <summary>
		///   修改图文素材列表中的文章接口
		/// </summary>
		/// <param name="mediaId"></param>
		/// <param name="index"></param>
		/// <param name="article"></param>
		/// <returns></returns>
		public async Task<WxBaseResp> UpdateArticleAsync(string mediaId, int index, WxArticleInfo article)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/update_news";
			LHttpRequest.CustomBody = JsonConvert.SerializeObject(new
			{
				media_id = mediaId,
				index = index,
				articles = article
			});
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///  上传永久素材接口
		/// </summary>
		/// <param name="mediaReq"></param>
		/// <returns></returns>
		public async Task<WxMediaUploadResp> UploadMediaAsync(WxMediaUploadReq mediaReq)
		{
			LHttpRequest LHttpRequest = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/add_material?type=" + mediaReq.type.ToString()
			};
			LHttpRequest.FileParameters.Add(new FileParameter("media", mediaReq.file_stream, mediaReq.file_name, mediaReq.content_type));
			if (mediaReq.type == WxMediaType.video)
			{
				LHttpRequest.FormParameters.Add(new FormParameter("description", string.Format("{{\"title\":\"{0}\", \"introduction\":\"{1}\"}}", mediaReq.title, mediaReq.introduction)));
			}
			return await base.RestCommonOffcialAsync<WxMediaUploadResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取视频【永久】素材下载地址
		/// </summary>
		/// <param name="mediaId">素材</param>
		/// <returns></returns>
		public async Task<WxMediaVedioUrlResp> GetMediaVedioUrlAsync(string mediaId)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/get_material",
				CustomBody = string.Format("{{\"media_id\":\"{0}\"}}", mediaId)
			};
			return await base.RestCommonOffcialAsync<WxMediaVedioUrlResp>(req, null);
		}

		/// <summary>
		///  下载【永久】素材文件
		///    视频  和  图文 请通过另外两个接口获取
		/// </summary>
		/// <param name="mediaId"></param>
		/// <returns></returns>
		public async Task<WxFileResp> DownloadMediaAsync(string mediaId)
		{
			WxOffAccessTokenResp wxOffAccessTokenResp = await this.GetAccessTokenFromCacheAsync();
			if (!wxOffAccessTokenResp.IsSuccess())
			{
				return ((ResultMo)wxOffAccessTokenResp).ConvertToResult<WxFileResp>();
			}
			return await new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/get_material?access_token=" + wxOffAccessTokenResp.access_token
			}.RestCommon(WxOffBaseApi.DownLoadFileAsync, null, "default");
		}

		/// <summary>
		///  删除【永久】素材
		/// </summary>
		/// <param name="mediaId">素材Id</param>
		/// <returns></returns>
		public async Task<WxBaseResp> DeleteMediaAsync(string mediaId)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/del_material",
				CustomBody = string.Format("{{\"media_id\":\"{0}\"}}", mediaId)
			};
			return await base.RestCommonOffcialAsync<WxBaseResp>(req, null);
		}

		/// <summary>
		///   获取素材总数
		/// </summary>
		/// <returns></returns>
		public async Task<WxMediaCountResp> GetMediaCountAsync()
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Get,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/get_materialcount"
			};
			return await base.RestCommonOffcialAsync<WxMediaCountResp>(req, null);
		}

		/// <summary>
		///   获取素材列表
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetMediaListResp> GetMediaListAsync(WxGetMediaListReq request)
		{
			LHttpRequest req = new LHttpRequest
			{
				HttpMothed = HttpMothed.Post,
				AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/material/batchget_material",
				CustomBody = JsonConvert.SerializeObject(request)
			};
			return await base.RestCommonOffcialAsync<WxGetMediaListResp>(req, null);
		}
	}
}
